package system.config.quartz.job;

import com.aliyun.oss.model.ListObjectsV2Result;
import com.aliyun.oss.model.OSSObjectSummary;
import common.model.po.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import system.config.aliyun.oss.OssService;
import system.config.quartz.util.JobEnum;
import system.service.SysUserService;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 描述
 *
 * @author 米泽鹏
 * @since 2024-1-13 上午 10:24
 */
@Slf4j
@Component
public class AvatarDeleteJob implements Job {

	@Resource
	private OssService ossService;
	@Resource
	private SysUserService userService;
	@Value("${aliyun.oss.bucketName}")
	private String bucketName;

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		log.info("开始执行定时任务：" + JobEnum.AvatarDeleteJob.getDescription());
		// 查询所有用户
		List<SysUser> userList = userService.lambdaQuery().select(SysUser::getAvatar).list();
		// 所有正在使用中的用户头像
		Set<String> avatarSet = userList.stream().map(SysUser::getAvatar).collect(Collectors.toSet());
		// 查询OSS上所有头像文件
		ListObjectsV2Result result = ossService.listObjects(bucketName, "avatar");
		// 需要删除的文件路径
		List<String> filePathList = result.getObjectSummaries().stream().map(OSSObjectSummary::getKey).filter(key -> !avatarSet.contains(key)).collect(Collectors.toList());
		// 批量删除
		if (!filePathList.isEmpty()) {
			ossService.deleteFiles(bucketName, filePathList);
		}
		log.info("定时任务 {} 执行完毕，删除文件数量：{}", JobEnum.AvatarDeleteJob.getDescription(), filePathList.size());
	}

}
